<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>变电站易损性计算</h4>
			<el-form :inline="true" ref="formRef" :rules="rules" label-position="right" :model="params" label-width="200px">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="编号：" class="form-item" prop="code">
							<el-input v-model="params.code" placeholder="" :disabled="true" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="年代：" class="form-item" prop="year">
							<el-input v-model="params.year" placeholder="请输入" :disabled="disabled" clearable />
							<!-- <el-select v-model="params.year" placeholder="请选择" class="form-select" :disabled="disabled" clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select> -->
						</el-form-item>
					</el-col>
					<!-- <el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="userName">
							<el-input v-model="params.userName" placeholder="" clearable />
						</el-form-item>
					</el-col> -->
				</el-row>

				<!-- <el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人所属单位：" class="form-item" prop="orgName">
							<el-input v-model="params.orgName" placeholder="" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间：" class="form-item" prop="createTime">
							<el-date-picker v-model="params.createTime" type="date" value-format="YYYY-MM-DD" placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row> -->

				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
							<el-select v-model="params.fortification" placeholder="请选择" class="form-select"
                                :disabled="disabled" clearable>
								<el-option v-for="item in optionList2" :label="item.dictItemName" :value="item.dictItemCode">
								</el-option>
                            </el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11"></el-col>
				</el-row>

				<el-row v-if="isAdd" justify="end">
					<el-form-item class="bottom-button">
						<!-- <el-button type="primary" @click="showUploadDialog = true">参数导入</el-button> -->
						<!-- <el-button type="primary" @click="onSort" v-if="route.query.id&&!route.query.operateType">排序</el-button> -->
						<el-button type="primary" @click="handleVerify" v-if="!route.query.id">验证</el-button>
                        <el-button type="primary" @click="onCalc" v-if="route.query.id">计算</el-button>
						<el-button type="primary" @click="onSubmit" v-if="route.query.id">提交</el-button>
					</el-form-item>
				</el-row>
			</el-form>
			<!-- 数据导入弹框 -->
			<import-data v-if="showUploadDialog" v-model="showUploadDialog" ref="uploadDialog"
				:uploadUrl="uploadUrl" downloadFileName="变电站易损性计算参数导入.xlsx"
				@importSuccess="onImport"></import-data>

			<el-form :inline="true" ref="tableRef" :rules="rules" label-position="right" :model="tableFormData">
				<h4 class="table-title">计算各个区间的失效概率</h4>
				<el-table class="listTable" ref="multipleTableRef" border :data="tableFormData.tableParamData" style="width: 100%"
					:cell-style="{ border: '1px solid #e5ebf7', }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column prop="siteNum" header-align="center" align="center" label="场址数" width="120"></el-table-column>
					<el-table-column header-align="center" align="center" label="样本数Zone ( j)">
						<template #default="scope">
							<el-form-item :prop="`tableParamData.${scope.$index}.samplesNumber`" :rules="rules.samplesNumber">
								<el-input v-model="scope.row.samplesNumber" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="最大地表加速度PGA j（g）">
						<template #default="scope">
							<el-form-item :prop="`tableParamData.${scope.$index}.pga`" :rules="rules.pga">
								<el-input v-model="scope.row.pga" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="damagesNumber" header-align="center" align="center" label="区间i设备损坏样本数 f (i)">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.damagesNumber`" :rules="rules.damagesNumber">
								<el-input v-model="scope.row.damagesNumber" :disabled="scope.row.disabled||!isAdd" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<!-- <el-table-column v-if="isAdd" fixed="right" label="操作" header-align="center" align="center" width="180">
						<template #default="scope">
							<el-popconfirm title="确认删除?" confirm-button-text="确认" cancel-button-text="取消"
								@confirm="deleteRow(scope.$index)">
								<template #reference>
									<el-button link type="text" size="small" @click="deleteRow(scope.$index)">删除</el-button>
								</template>
							</el-popconfirm>
							<el-button link type="text" size="small" @click="deleteRow(scope.$index)">删除</el-button>
						</template>
					</el-table-column> -->
				</el-table>
				<!-- <el-button v-if="isAdd" class="add" style="width: 100%;margin:0 0 20px 0;" plain
					@click="handleCalcAdd(tableFormData.tableParamData)">
					<el-icon style="vertical-align: middle">
						<Plus />
					</el-icon>
				</el-button> -->
			</el-form>

			<el-form :inline="true" ref="tableCalcRef" :rules="rules" label-position="right" :model="tableFormData">
				<!-- <el-row justify="end" class="table-tools-btn">
					<el-button v-if="isAdd" type="primary" @click="onCalc">计算</el-button>
				</el-row> -->
				<el-table class="listTable" ref="multipleTableRef" border :data="tableFormData.tableData" style="width: 100%"
					:cell-style="{ border: '1px solid #e5ebf7', }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column prop="range" header-align="center" align="center" label="区间"></el-table-column>
					<el-table-column prop="siteNum" header-align="center" align="center" label="场址数" />
					<el-table-column prop="pgai" header-align="center" align="center" width="260">
						<template #header>
							<!-- 公式 -->
							<MultilineFormula display="block" tagOffset="-6px" :option="[
								{ content: 'PGA' },
								{ content: '(i)' },
								{ content: '=' },
								{ content: '[' },
								{ content: '∑', scale: 1.5, topContent: 'J', bottomContent: 'j=1' },
								{ content: 'Z', sub: 'one' },
								{ content: '(j)' },
								{ content: 'P', sub: 'GAj' },
								{ content: ']' },
								{ content: '/' },
								{ content: 'Z', sub: 'one' },

							]">
							</MultilineFormula>
						</template>
						<template #default="{ row }">{{ row.pgai }}</template>
					</el-table-column>
					<el-table-column prop="samplesAcc" header-align="center" align="center" label="设备累积样本数 N(i)" />
					<el-table-column prop="rangeCount" header-align="center" align="center" label="区间i的设备总数n(i)" />
					<el-table-column prop="rangeBreakCount" header-align="center" align="center" label="区间i设备损坏样本数 f (i)">
						<!-- <template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.rangeBreakCount`" :rules="rules.rangeBreakCount">
								<el-input v-model="scope.row.rangeBreakCount" :disabled="scope.row.disabled||!isAdd" size="small"
									type="number"></el-input>
							</el-form-item>
						</template> -->
					</el-table-column>
					<el-table-column prop="ril" header-align="center" align="center">
						<template #header>
							<!-- 公式 -->
							<MultilineFormula display="block" :option="[
								{ content: 'r' },
								{ content: '(i)' },
								{ content: '=' },
								{ content: '1-' },
								{
									rows: [
										[{ content: 'f(i)' }],
										[{ content: 'N(i)' }],
									]
								}
							]">
							</MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column prop="rir" header-align="center" align="center" width="170">
						<template #header>
							<!-- 公式 -->
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'R(i)' },
								{ content: '=', margin: '0 8px' },
								{ content: 'R(i-1)r(i)' },
							]"></Formula>
						</template>
					</el-table-column>
					<el-table-column prop="fi" header-align="center" align="center" width="140">
						<template #header>
							<!-- 公式 -->
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'F(i)' },
								{ content: '=', margin: '0 8px' },
								{ content: '1-R(i)' },
							]"></Formula>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="修正值">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.fiCorrect`"
								:rules="rules.fiCorrect">
								<el-input v-model="scope.row.fiCorrect" :disabled="scope.row.disabled"
									size="small" type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
				</el-table>
			</el-form>

			<!-- <el-row justify="end">
				<el-button type="primary" style="margin:20px 0;">生成曲线</el-button>
			</el-row>
			<div class="div-chart" ref="chartRef"></div> -->
			<!-- 版本查看 -->
			<GetVersion v-if="openDialog" v-model:open="openDialog" @recalculateVersion="recalculateVersion" type="6"/>
			<el-dialog v-model="dialogVisible" @close="cancle" title="提示" width="500px">
					<p v-for="item in messageList">{{ item.label }}
						<el-popover placement="bottom" title="提示详情" :width="200" trigger="click">
							<template #reference>
								<span style="color: #107ce5;cursor: pointer;">提示详情</span>
							</template>
							<template #default>
								<p v-for="val in item.value">{{ val }}</p>
							</template>
						</el-popover>
					</p>
					<p>&nbsp;</p>
			</el-dialog>
		</div>
	</div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from "@/utils/ruoyi.js";
// 接口
import { getInfo } from '@/api/login'
import { getUserId } from "@/utils/auth";
// 获取接口
import {
	getByIdAndType, //查询
	groupTsVulnerability, //排序
	caTsVulnerability, //计算
	saveTsVulnerability, //保存
	importTsVulnerabilityUrl, //参数导入
	recalculateCaTs,//验证
	saveCaTsfResult,//计算并保存
} from "@/api/lifelineVulnerAnalysis/lifelineVulnerAnalysis.js";
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 引入公式组件
import Formula from '@/components/Formula';
import MultilineFormula from '@/components/Formula/multiline';
import GetVersion from '../underPipeNet/dataFile/Version.vue';
// 引入导入弹框
import ImportData from "@/components/ImportData";

// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 当前实例
const { proxy } = getCurrentInstance();
// 当前路由
const route = useRoute();
const router = useRouter();
// 打开类型，query为查看
let operateType = computed(() => route.query.operateType||false);
// 是否是新增页，有路由参数是详情页，否则是新增页
let isAdd = computed(() => (route.query.id && route.query.operateType ? false : true));
// 表单对象
const formRef = ref();
const tableRef = ref();
//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().length!=4) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().indexOf(".")!=-1) {
    callback(new Error('请输入yyyy格式如2022'));
  } else {
    callback();
  }
}
const data = reactive({
	// 表单参数
	params: {
		code: "",//编号
		year: "",//年代
		fortification: "", //设防情况
		createTime: parseTime(new Date()), //维护时间
		userName: userName.value, //维护人
		orgName: orgName.value, //维护人所属单位  
		notes: "",//备注
	},
	fortificationOptions: dictStore.fortificationOptions || [],
	yearsOptions: dictStore.yearsOptions1 || [],
	// 表单验证规则
	rules: {
		fortification: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		year:  [{
				required: true,
				message: "请输入正确数值",
				validator: isYearNotMust,
				trigger: ["change", "blur"],
			}],
		// 场址数
		siteNum: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		// 样本数
		samplesNumber: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		// 最大地表加速度PGA
		pga: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		samplesAcc: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		rangeCount: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
		damagesNumber: [
			{ required: true, message: '请输入', trigger: 'blur' }
		],
	},
	//表格
	tableFormData: {
		tableParamData: [
			// {
			// 	siteNum: 1, //场址数
			// 	samplesNumber: '',
			// 	pga: '',
			// }
		],
		tableData: [
			// {
			// 	siteNum: '', //场址数
			// 	range: '', //区间
			// 	samplesAcc: "", //设备累积样本数 N(i)
			// 	rangeCount: "", //区间i的设备总数n(i)
			// 	pgai: "",
			// 	rangeBreakCount: "",
			// 	ril: '',
			// 	rir: '',
			// 	fi: '',
			// },
		],
	}
});

const {
	params,
	fortificationOptions,
	yearsOptions,
	rules,
	tableFormData
} = toRefs(data);

const disabled = ref(false);
//表格
const multipleTableRef = ref();
//表格新增行
const handleCalcAdd = (tableData) => {
	const objRow = {
		siteNum: 1,
		samplesNumber: '',
		pga: '',
	};
	if (tableData && tableData.length) {
		const lastItem = tableData[tableData.length - 1];
		// 场址数自增
		objRow.siteNum = (lastItem.siteNum || 0) + 1;
	}
	tableData.push(objRow);
};
//删除行
const deleteRow = (index) => {
	tableFormData.value.tableParamData.splice(index, 1);
}

// 获取用户
function getUserInfo(userId) {
	getInfo(userId || getUserId()).then(response => {
		params.value.userName = response.user.userName;
		params.value.orgName = response.user.orgName;
	});
};

//排序
const onSort = async () => {
	// 表单验证
	const formElValid = await proxy.$refs['formRef'].validate((valid, fields) => { valid, fields });
	const tableElValid = await proxy.$refs['tableRef'].validate((valid, fields) => { valid, fields });
	if (formElValid && tableElValid) {
		let query = [];
		if (tableFormData.value.tableParamData && tableFormData.value.tableParamData.length) {
			query = [...tableFormData.value.tableParamData];
		} else {
			proxy.$modal.msgWarning("请先在下表中输入样本数Zone和最大地表加速度PGA后再进行排序！");
			return false;
		}
		groupTsVulnerability(query).then((res) => {
			const { code, data, message } = res;
			if (code === 200 && data) {
				proxy.$modal.msgSuccess("排序成功！");
				const resData = [];
				for (const key in data) {
					const item = data[key];
					if (item) {
						resData.push({
							siteNum: item.siteNum || '', //场址数
							range: item.intensity, //区间
							samplesAcc: item.N, //设备累积样本数 N(i)
							rangeCount: item.numberSites, //区间i的设备总数n(i)
							pgai: item.pga,
							rangeBreakCount: "", //设备损坏样本数
						});
					}
				}
				tableFormData.value.tableData = resData;
			}
		}).catch(err => {
			console.log(err);
		});
	}
}

// 导入弹框是否显示
let showUploadDialog = ref(false);
// 导入数据接口路径
const uploadUrl = ref(importTsVulnerabilityUrl);
// 导入成功回调
const onImport = (response, uploadFile, uploadFiles) => {
	const { code, data } = response;
	if (code == 200 && data) {
		proxy.$modal.msgSuccess('导入数据成功!');
		// 列表数据回显
		tableFormData.value.tableParamData = [];
		tableFormData.value.tableData = [];
		if(data && data.length) {
			data.map(item => {
				const objCur = {
					...item,
					siteNum: item.siteNum || item.range
				}
				tableFormData.value.tableParamData.push(objCur);
				tableFormData.value.tableData.push(objCur);
			})
		}
	}
}
//变电站计算
const onCalc = async (row) => {
	// 表单验证
	const formElValid = await proxy.$refs['formRef'].validate((valid, fields) => { valid, fields });
	const tableElValid = await proxy.$refs['tableCalcRef'].validate((valid, fields) => { valid, fields });
	if (formElValid && tableElValid) {
		proxy.$modal.loading('正在努力计算,请耐心等待！');
		caTsVulnerability(tableFormData.value.tableParamData).then((res) => {
			proxy.$modal.closeLoading();
			const { code, data } = res;
			if (code === 200 && data) {
				proxy.$modal.closeLoading();
				tableFormData.value.tableData = data;
				proxy.$modal.msgSuccess('计算完成！计算结果未保存，若需保存结果，请计算后点击提交按钮！');
			} else {
				proxy.$modal.closeLoading();
				proxy.$modal.msgError('计算失败');
			}
		}).catch(err => {
			proxy.$modal.closeLoading();
			console.log(err.message);
		});
	}
};

//变电站保存
const onSubmit = async() => {
	// 表单验证
	const formElValid = await proxy.$refs['formRef'].validate((valid, fields) => { valid, fields });
	const tableElValid = await proxy.$refs['tableCalcRef'].validate((valid, fields) => { valid, fields });
	if (formElValid && tableElValid) {
		let query = {
			type:'6',
			tsParam:tableFormData.value.tableParamData,
			valueParam:tableFormData.value.tableData,
		}
		proxy.$modal.loading('正在保存,请耐心等待！');
		saveTsVulnerability(query).then((res) => {
			const { code, data, message } = res;
			if (code === 200) {
				tableFormData.value.tableData = data;
				proxy.$modal.closeLoading();
				proxy.$modal.msgSuccess("保存成功!");
				// 延迟跳转
				setTimeout(() => {
					router.push('/lifelineVulnerAnalysis/lifelineMain')
				}, 1500)
			}
		}).catch(err => {
			proxy.$modal.closeLoading();
			console.log(err.message);
		});
	} else {
		proxy.$refs['formRef'].scrollToField(Object.keys(fields)[0]);
	}
}

// 显示弹框
const openDialog = ref(false)
const handleVerify = () => {
	openDialog.value = true;
}
// 验证
const messageList = ref([]);
const dialogVisible = ref(false);
const cancle = () => {
	dialogVisible.value = false;
}
const recalculateVersion = (version) => {
	openDialog.value = false;
	recalculateCaTs({ versionId:version.id, type: '6' }).then(res => {
		if (JSON.stringify(res.data) == '{}') {
			ElMessageBox.confirm(
				'数据通过验证，是否计算？', '提示',
				{
					confirmButtonText: '计算并保存',
					cancelButtonText: '取消',
					type: 'success',
				}
			)
				.then(() => {
					saveCaTsfResult({versionId:version.id}).then(response=>{
						if(response.code==200){
							router.push(`/lifelineVulnerAnalysis/lifelineMain?type=6`)
						}
					})
				}).catch(() => { })
		} else {
			const { data } = res;
			messageList.value = [];
			for (let i in data) {
				messageList.value.push({ label: `第${i}行计算参数未填写完整，请补充完整再计算。`, value: data[i] })
			}
			dialogVisible.value = true;
		}
	})
}

// 根据参数获取详情信息
function getData(parmas) {
	getByIdAndType(parmas).then((res) => {
		const { code, data, message } = res;
		if (code === 200 && data) {
			const { tableEntity,tsListVo,tsValueListVo, mtolProjectEntity, ctVulnerabilityResultList } = data;
			// 基础信息
			if (tableEntity) {
				params.value = { ...tableEntity };
				const dateTime = new Date()
				params.value.createTime = parseTime(dateTime);
				// 根据id获取用户信息
				params.value.userName = userStore.name;
				params.value.orgName = userStore.orgName;
			}
			// 参数表格
			tableFormData.value.tableParamData.value = [];
			//循环遍历之前加上非空判断
			if (tsListVo && tsListVo.length >= 0) {
				tsListVo.forEach((item, index) => {
					item.isEdit = false;
					item.disabled = operateType.value === 'query' ? true : false;
					item.siteNum = index + 1;
					item.tsId = tableEntity.id;
				});
				tableFormData.value.tableParamData = [...tsListVo];
			}
			if(tsValueListVo) {
				tableFormData.value.tableData = [ ...tsValueListVo ];
				tableFormData.value.tableData.forEach((item, index) => {
					item.disabled = operateType.value === 'query' ? true : false;
				});
			}
		}
	}).catch(err => {
		console.log(err.message);
	});
}

//字典表查询
const optionList1 = ref([])
const optionList2 = ref([])
/** 获取字典值 */
async function getDictData() {
    await getValidDictItemsByDictCode("smxjsnd").then(response => {
        optionList1.value = response.data;//建造年代
    });
    await getValidDictItemsByDictCode("smxsfqk").then(response => {
        optionList2.value = response.data;//设防情况
    });
}

getDictData();

// 挂载
onMounted(() => {
	// 读取路由参数
	const id = route.query.id;
	if (id) {
		disabled.value = true;
		// 根据参数获取详情信息
		getData({ type:6, id });
	} else {
		disabled.value = false;
	}
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}

	// 表格标题
	.table-title {
		margin-top: 50px;
	}
	// 表格工具按钮组
	.table-tools-btn {
		margin: 20px 0;
		float: right;
	}
	.table-title+.table-tools-btn{
		margin: 0;
		margin-top: -50px;
	}
}
</style>


